using System.Numerics;
using Digitalmes.Domain.Entities.Mes.Qualities;

namespace Digitalmes.Application.Mes.Qulities.Defects.Commands;

/// <summary>
/// 缺陷定义更新命令。
/// </summary>
public sealed record UpdateDefectCommand(long Id, QcDefectDefineDto Defect) : IRequest<IResult<bool>>;

internal sealed class UpdateDefectCommandHandler(IRepository<QcDefectDefine> repo) : IRequestHandler<UpdateDefectCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateDefectCommand request, CancellationToken cancellationToken)
    {
        if (await repo.IsAnyAsync(m => m.DefectCode == request.Defect.DefectCode && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("缺陷代码已存在");
        }

        var defect = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (defect == null)
        {
            return Result.Failure("未找到要更新的缺陷");
        }

        defect.DefectCode = request.Defect.DefectCode;
        defect.DefectName = request.Defect.DefectName;
        defect.DefectType = request.Defect.DefectType;
        defect.DefectTypeDesc = request.Defect.DefectTypeDesc;
        defect.DefectLevel = request.Defect.DefectLevel;
        defect.DefectDesc = request.Defect.DefectDesc;
        defect.Order = request.Defect.Order;
        defect.Status = request.Defect.Status;

        var ok = await repo.UpdateAsync(defect, m => new
        {
            m.DefectCode,
            m.DefectName,
            m.DefectType,
            m.DefectTypeDesc,
            m.DefectLevel,
            m.DefectDesc,
            m.Order,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
